package com.hjx.security;

import com.hjx.util.JwtAuthTokenUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/5/27 - 20:45
 */
@Service
public class JwtAuthService {

    @Resource
    AuthenticationManager authenticationManager;
    @Resource
    private JwtAuthTokenUtil jwtAuthTokenUtil;
    /**
     * 登录认证换取JWT令牌
     *
     * @return token
     */
    public String login(String username, String password) throws AuthenticationException {
        //用username和password来获取认证令牌
        UsernamePasswordAuthenticationToken upToken =
                new UsernamePasswordAuthenticationToken(username, password);

        //一般的流程 UsernamePasswordAuthenticationFilter
        //登录认证 在这会调用UserDetailsService中的loadUserByUsername()方法获取信息 然后进行密码的验证

        //实际是由ProviderManager一个一个的寻找可以提供认证的提供者
        //UsernamePasswordAuthenticationToken 的认证提供者是AbstractUserDetailsAuthenticationProvider这个抽象类
        //这个抽象类的实现类为DaoAuthenticationProvider 实际调用UserDetailsService中的loadUserByUsername()方法就是在这里进行的
        //密码的验证也是DaoAuthenticationProvider来进行验证的
        Authentication authenticate = authenticationManager.authenticate(upToken);

        User user = (User) authenticate.getPrincipal();

//        return jwtTokenUtil.generateToken(user);
        return jwtAuthTokenUtil.createToken(user.getUsername());
    }


    public String refreshToken(String oldToken) {
        //不过期则刷新token
        if (!jwtAuthTokenUtil.isTokenExpired(oldToken)) {
            return jwtAuthTokenUtil.refreshToken(oldToken);
        }
        //过期就返回null
        return null;
    }
}
